﻿using BlueWind.Mediator.ServiceContracts;
using BlueWind.Mediator.ServiceContracts.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;

namespace BlueWind.Mediator.Server
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class ColleaguePrototypeManager : Prototype, IColleaguePrototypeManager
    {
        public static ColleaguePrototypeManager colleagueManager;
        public static Mediator GlobalMediator = new Mediator();
        private Dictionary<BwConnection, Callback> callBackDictionary = new Dictionary<BwConnection, Callback>();
        private Dictionary<BwConnection, IColleague> prototypes = new Dictionary<BwConnection, IColleague>();

        public Dictionary<BwConnection, Callback> CallBackDictionary
        {
            get { return callBackDictionary; }
            set { callBackDictionary = value; }
        }

        public Dictionary<BwConnection, IColleague> Prototypes
        {
            get
            {
                return prototypes;
            }
            set
            {
                prototypes = value;
            }
        }

        public IColleague this[BwConnection index]
        {
            get
            {
                return prototypes[index];
            }
            set { prototypes[index] = value; }
        }

        public Mediator Mediator
        {
            get
            {
                throw new System.NotImplementedException();
            }
            set
            {
            }
        }

        public void Add(IColleague prototye, BwConnection name)
        {
            if (!callBackDictionary.ContainsKey(name)) callBackDictionary.Add(name, new Callback(prototye.Receive));
            prototypes.Add(name, prototye);
        }

        public Boolean Contains(int userID)
        {
            var query = from connection in prototypes.Keys
                        where connection.UserID == userID
                        select connection;
            if (query.FirstOrDefault() != null) return true;
            return false;
        }

        public int GetCount()
        {
            return prototypes.Count;
        }

        public void Remove(BwConnection key)
        {
            prototypes.Remove(key);
        }

        public void Send(BwConnection connection, BwMessage message, MessageType messageType)
        {
            if (callBackDictionary.Keys.Contains(connection))
                if (callBackDictionary[connection] != null)
                {
                    if (((ICommunicationObject)ColleaguePrototypeManager.colleagueManager[connection]).State == CommunicationState.Opened)
                        callBackDictionary[connection]("Administrator", "Globe", message, messageType);
                }
        }
    }
}